package com.his.modules.business.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.his.core.utils.StringUtils;
import com.his.modules.business.dto.HisShareBrzh;
import com.his.modules.business.entity.MsCf01;
import com.his.modules.business.entity.MsCf02;
import com.his.modules.business.entity.MsSfmx;
import com.his.modules.business.entity.YfYflb;
import com.his.modules.business.service.MsCf01Service;
import com.his.modules.business.service.MsCf02Service;
import com.his.modules.business.service.YfYflbService;
import com.his.modules.common.util.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class YfMzmkMzfyUtil {

    private static MsCf01Service msCf01Service;
    private static MsCf02Service msCf02Service;
    private static YfYflbService yfYflbService;
    private static String isError;
    //窗口编号
    private static Integer iiCkbh;
    //库存窗口编号
    private static Integer iiKcck;
    //缺药可发药标志
    private static Integer iiQykfybz;
    //配药核对 1:启用,0:不启用
    private static Integer iiPyhd;
    //包装类别    1:门诊   2:住院
    private static Integer iiBzlb;
    //药房识别
    private static Long iiYfcode;
    //共享处方变量吧，省得来回传参
    private static MsCf01 iuoMsCf01;
    //配药人(一体化服务平台)
    private static String isPyr = "YTHFWPT";

    private static HisShareBrzh hisShareBrzh = new HisShareBrzh();

    private static String isFphm;
    //识别序号
    private static Long ilSbxh;
    //计费标记
    private static Integer iiJfbz;
    //收费明细
    private static List<MsSfmx> msSfmxList = new ArrayList<>();
    //处方02
    private static List<MsCf02> msCf02List = new ArrayList<>();

    @Autowired
    public void setMsCf01Service(MsCf01Service msCf01Service) {
        this.msCf01Service = msCf01Service;
    }

    @Autowired
    public void setMsCf02Service(MsCf02Service msCf02Service) {
        this.msCf02Service = msCf02Service;
    }

    @Autowired
    public void setYfYflbService(YfYflbService yfYflbService) {
        this.yfYflbService = yfYflbService;
    }

    //    u_public_datastore idw_cf01 //处方01
//    u_public_datastore idw_cf02  //处方02
//    u_public_datastore idw_mzxx
//    u_public_datastore idw_sfmx
//    u_yfpublic_yf_updatekcmx   uo_kcmx
//    Transaction SQLHIS,SQLTemp
//    u_yfpublic_kcdj iu_kcdj  //冻结库存管理模块
//    u_public_object iu_mhyj_yjcl
//    string is_yj
//    long il_cfsb,il_sbxh,il_brid
//    string is_error,is_fphm
//    string is_pyr
//    int ii_jfbz
//    s_his_share_brzh is_brzh
//    u_zh_public_account iu_account

    /**
     * 返回错误信息
     * @return
     */
    public static String getIsError() {
        return isError;
    }

    public static Integer init(String cfhm, Integer fyck) {
        //每次进来先置空
        iuoMsCf01 = null;

        iiCkbh = fyck;

        Integer liSjglbz;
        QueryWrapper<MsCf01> msCf01QueryWrapper = new QueryWrapper<>();
        msCf01QueryWrapper.eq("cfhm", cfhm);
        msCf01QueryWrapper.eq("zfpb", 0);
        MsCf01 msCf01 = msCf01Service.getOne(msCf01QueryWrapper);
        if(Objects.isNull(msCf01)) {
            isError = "查无此处方信息";
            return -1;
        }
        iuoMsCf01 = msCf01;
        iiYfcode = msCf01.getYfsb();
        refresh(msCf01.getCfsb());

        YfYflb yfYflb = yfYflbService.getById(iiYfcode);
        liSjglbz = yfYflb.getSjglbz();

        if(liSjglbz == 1) {
            iiKcck = iiCkbh;
        } else {
            iiKcck = 0;
        }
        iiBzlb = yfYflb.getBzlb();
        //取缺药可发药标志
        iiQykfybz = Integer.parseInt(CommonUtils.getGyXtcs(yfYflb.getJgid().toString(), "MZQYKFYBZ" + iiYfcode, "1", "门诊缺药可发临时禁用药标志"));
        //取配药核对启用标志
        iiPyhd = Integer.parseInt(CommonUtils.getGyXtcs(yfYflb.getJgid().toString(),"PYHD" + iiYfcode,"1","配药核对1:启用,0:不启用"));

//        //设置显示的收费精度
//        Integer li_decnum
//        String ls_format
//        idw_cf02.Object.sum_t.Format = "0.00"
//        idw_cf02.Modify("sum_t.expression = 'sum(round(ypsl*ypjg*cfts,2)for all)'")
//
//        //初始化冻结库存管理模块
//        iu_kcdj = create u_yfpublic_kcdj
//        if gb_yjxtqy then iu_mhyj_yjcl = Create using 'u_mhyj_yjjk' //应急处理
        return uffy();
    }

    private static Integer issueprocess(String asPyr, Integer aiFyfs) {
//        s_yfpublic_yf_updatekcmx	lstr_kcmx[]
//        DateTime 	ldt_CurDT //当前时间
//        Long     	ll_cfsb ,ll_jlxh,ll_sbxh,ll_fyck //cf02处方识别,YF_MZFYMX识别序号,cf02中的识别序号
//        Long      	ll_ypxh,ll_ypcd,ll_cfts,ll_Row,ll_yfbz_new,ll_yfbz_old,ll_zxbz
//        String 	 	ls_yfgg,ls_yfdw,ls_fphm
//        Integer		li_RtnRows,i,li_cflx,li_yplx //处方类型,药品类型
//        // 修改精度
//        Dec{4}		ldc_Rtnlsje,ldc_Rtnpfje,ldc_Rtnjhje,ld_ypje_old
//        Dec{4}		ldc_ylse,ldc_ypfe,ldc_xlse,ldc_xpfe
//        DEC{4}      ld_ypsl
//        Dec{6}		ldc_lsjg,ldc_pfjg,ldc_jhjg,ld_ypdj_old
//        Long    		ll_fybz,ll_zfpb
//        Dec{0}		ldc_jbywbz //基本药物标志
//        Boolean		ib_yj = TRUE
//        long			ll_countcf
//        ldt_CurDT = gf_server_date()
//        ll_cfsb = idw_cf01.Object.cfsb[idw_cf01.GetRow()]
//        //=================================================================
//        // YWLX = 101 处方发药
//        //=================================================================
//        uo_kcmx.uf_set_ywxx(101,ldt_CurDT)
//
//        For ll_Row = 1 TO idw_cf02.RowCount()
//        ll_ypxh =  idw_cf02.Object.ypxh[ll_Row]
//        ll_ypcd =  idw_cf02.Object.ypcd[ll_Row]
//        ll_cfts =  idw_cf02.Object.cfts[ll_Row]
//        ld_ypsl = idw_cf02.Object.ypsl[ll_Row]
//        If IsNull(ll_cfts) Then ll_cfts = 1
//        ll_yfbz_old = idw_cf02.Object.yfbz[ll_Row]
//        ld_ypdj_old = idw_cf02.Object.ypjg[ll_Row]
//
//        SELECT YF_YPXX.YFBZ,YK_TYPK.ZXBZ,YF_YPXX.YFGG,YF_YPXX.YFDW,YK_TYPK.JBYWBZ INTO:ll_yfbz_new,:ll_zxbz,:ls_yfgg,:ls_yfdw,:ldc_jbywbz
//        FROM YK_TYPK,YF_YPXX
//        WHERE YK_TYPK.YPXH = YF_YPXX.YPXH   AND
//        YF_YPXX.YPXH = :Ll_Ypxh  AND
//        YF_YPXX.YFSB = :ii_yfcode AND
//        YF_YPXX.JGID = :go_jgxx.il_jgid USING SQLHIS;
//        //增加读取基本药物标志，jbywbz
//        If ll_yfbz_new > 0 Then
//                ld_ypsl = Round(ld_ypsl * ll_cfts * ll_yfbz_old / ll_yfbz_new,4) // 转换成当前药房数量
//        ld_ypdj_old = Round(ld_ypdj_old * ll_yfbz_new / ll_yfbz_old ,6) // 转换成当前药房价格
//        End If
//        SetNull(lstr_kcmx[1].ypph)
//        SetNull(lstr_kcmx[1].ypxq)
//        lstr_kcmx[1].ypsl = - ld_ypsl
//        lstr_kcmx[1].lsjg = ld_ypdj_old
//        lstr_kcmx[1].pfjg = 0
//        lstr_kcmx[1].jhjg = 0
//        lstr_kcmx[1].lsje = Round(ld_ypsl * ld_ypdj_old,4)
//        lstr_kcmx[1].pfje = 0
//        lstr_kcmx[1].jhje = 0
//        lstr_kcmx[1].kcsb = 0
//        //应急处理
//        If gb_yjxtqy Then
//        If iu_mhyj_yjcl.DYNAMIC uf_getyxzt() = 1 Then ib_yj = FALSE
//        End If
//        If ib_yj Then
//        If ii_qykfybz = 1 Then //被药房临时禁用的药品在缺药时门诊也可以发
//        If NOT uo_kcmx.of_UpdateKCMX_all(ii_yfcode,ii_kcck,ll_ypxh,ll_ypcd,lstr_kcmx[],li_RtnRows,ldc_Rtnlsje,ldc_Rtnpfje,ldc_Rtnjhje,TRUE) Then
//                is_error = uo_kcmx.of_GetErrText()
//        Return -1
//        End If
//        Else
//        If NOT uo_kcmx.of_UpdateKCMX(ii_yfcode,ii_kcck,ll_ypxh,ll_ypcd,lstr_kcmx[],li_RtnRows,ldc_Rtnlsje,ldc_Rtnpfje,ldc_Rtnjhje,TRUE) Then
//                is_error = uo_kcmx.of_GetErrText()
//        Return -1
//        End If
//        End If
//        li_cflx = idw_cf01.Object.cflx[idw_cf01.GetRow()]
//        ls_fphm = idw_cf01.Object.fphm[idw_cf01.GetRow()]
//        li_yplx = idw_cf02.Object.xmlx[ll_Row]
//        ll_sbxh = idw_cf02.Object.sbxh[ll_Row]
//        ll_jlxh = of_Getid("YF_MZFYMX",li_RtnRows)
//
//        For i = 1 TO li_RtnRows
//        ld_ypje_old = Round(lstr_kcmx[i].ypsl * ld_ypdj_old,4)
//        //增加写基本药物标志，jbywbz
//        INSERT INTO YF_MZFYMX ( JGID , JLXH , YFSB , FYCK , FYRQ , CFSB , CFLX ,
//                FPHM , SBXH , YPXH , YPCD , YPLX , YPGG , YFDW , YFBZ , YPSL ,
//                HJJG , LSJG , PFJG , JHJG ,
//                HJJE , LSJE , PFJE , JHJE , YPPH , YPXQ ,TYGL ,YKJH ,JBYWBZ,KCSB)
//        VALUES ( :go_jgxx.il_jgid ,:ll_jlxh , :ii_yfcode , :ii_Ckbh , :ldt_CurDT , :ll_cfsb , :li_cflx ,
//				:ls_fphm , :ll_sbxh , :ll_ypxh , : ll_ypcd , :li_yplx , :ls_yfgg , :ls_yfdw , :ll_yfbz_new , :lstr_kcmx[i].ypsl ,
//				:ld_ypdj_old , :lstr_kcmx[i].lsjg , :lstr_kcmx[i].pfjg , :lstr_kcmx[i].jhjg,
//				:ld_ypje_old , :lstr_kcmx[i].lsje , :lstr_kcmx[i].pfje , :lstr_kcmx[i].jhje, :lstr_kcmx[i].ypph , :lstr_kcmx[i].ypxq , :ll_jlxh , :lstr_kcmx[i].YKJH,:ldc_jbywbz,:lstr_kcmx[i].kcsb) USING SQLHIS;
//        If SQLHIS.SQLCode <> 0 Then
//                is_error = SQLHIS.SQLErrText
//        Return -1
//        End If
//        ll_jlxh ++
//        Next
//        End If
//        //
//
//        Next
//        //更新CF01的发药日期，发药工号，发药标志，发药窗口
//        SELECT FYBZ,ZFPB,FYCK INTO :ll_fybz,:ll_zfpb,:ll_fyck FROM MS_CF01 Where cfsb = :ll_cfsb AND JGID = :go_jgxx.il_jgid USING SQLHIS;
//        If ll_fybz > 0 Then
//                is_error = '注意：该处方单已被别的窗口发出!'
//        Return -1
//        End If
//        If ll_zfpb = 1 Then
//                is_error = '注意：该处方单已被作废!'
//        Return -1
//        End If
//        Choose Case ai_fyfs
//        Case 1 //正常发药方式
//        UPDATE MS_CF01 Set FYRQ = :ldt_CurDT,FYGH = :go_User.UserID,FYBZ = 1,PYGH = :as_pyr,PYBZ = 1,YFSB = :ii_yfcode Where cfsb = :ll_cfsb AND FYBZ = 0 AND ZFPB = 0 AND JGID = :go_jgxx.il_jgid USING SQLHIS;
//        Case 2 //配药发药方式
//        if is_pyhd = "1" then  //配药核对启用
//        UPDATE MS_CF01 Set FYRQ = :ldt_CurDT,FYGH = :go_User.UserID,FYBZ = 1,YFSB = :ii_yfcode Where cfsb = :ll_cfsb AND FYBZ In (0,-1) AND ZFPB = 0 AND JGID = :go_jgxx.il_jgid USING SQLHIS;
//		else
//        //配药核对不启用是核对人默认为发药人，核对时间默认为发药时间
//        UPDATE MS_CF01 Set HDGH = :go_user.userid,HDRQ = :ldt_CurDT,FYRQ = :ldt_CurDT,FYGH = :go_User.UserID,FYBZ = 1,YFSB = :ii_yfcode Where cfsb = :ll_cfsb AND FYBZ In (0,-1) AND ZFPB = 0 AND JGID = :go_jgxx.il_jgid USING SQLHIS;
//        end if
//        Case 3 //一卡通发药方式
//        UPDATE MS_CF01 Set FYRQ = :ldt_CurDT,FYGH = :go_User.UserID,FYBZ = 1,PYGH = :as_pyr,PYBZ = 1,YFSB = :ii_yfcode Where cfsb = :ll_cfsb AND FYBZ = 0 AND ZFPB = 0 AND JGID = :go_jgxx.il_jgid USING SQLHIS;
//        End Choose
//
//        If SQLHIS.SQLCode <> 0 OR SQLHIS.SQLNRows = 0 Then
//        If SQLHIS.SQLCode <> 0 Then
//                is_error = SQLHIS.SQLErrText
//        Else
//                is_error = "未找到更新记录或更新记录已变动!"
//        End If
//        Return -1
//        End If
//        //保存应急处方识别
//        If ib_yj = false Then
//        If iu_mhyj_yjcl.DYNAMIC uf_getyjdb() = 1 Then
//        INSERT INTO MHYJ_YJCF( CFSB ,KKCBZ) Values (:ll_cfsb,0) USING SQLHIS;
//        If SQLHIS.SQLCode <> 0 Then
//                is_error = SQLHIS.SQLErrText
//        Return -1
//        End If
//        End If
//        ELSE
//        If gb_yjxtqy Then
//                ll_countcf = 0
//        If iu_mhyj_yjcl.DYNAMIC uf_getyjdb() = 0 Then
//        IF ll_cfsb < 0 THEN
//        SELECT COUNT(1) INTO :ll_countcf FROM MHYJ_YJCF WHERE CFSB = :ll_cfsb USING SQLHIS;
//        IF SQLHIS.SQLCODE <> 0 THEN
//                is_error = SQLHIS.SQLErrText
//        Return -1
//        ELSEIF ll_countcf = 0 THEN
//        INSERT INTO MHYJ_YJCF( CFSB ,KKCBZ) Values (:ll_cfsb,1) USING SQLHIS;
//        If SQLHIS.SQLCode <> 0 Then
//                is_error = SQLHIS.SQLErrText
//        Return -1
//        End If
//        ELSE
//        UPDATE MHYJ_YJCF SET KKCBZ = 1 WHERE CFSB = :ll_cfsb USING SQLHIS;
//        If SQLHIS.SQLCode <> 0 Then
//                is_error = SQLHIS.SQLErrText
//        Return -1
//        End If
//        END IF
//        END IF
//        END IF
//        END IF
//        End If
//        //解冻指定处方的冻结库存
//        If iu_kcdj.uf_kcjd(ll_cfsb) < 0 Then
//                is_error = iu_kcdj.uf_geterror()
//        Return -1
//        End If
//
//        // 只有收费分配的窗口和药房发药窗口一致才减排队处方数，否则会出现负数
//        IF ll_fyck = ii_Ckbh THEN
//        UPDATE YF_CKBH Set PDCF = PDCF - 1 Where YFSB = :ii_yfcode AND CKBH = :ii_Ckbh AND JGID = :go_jgxx.il_jgid USING SQLHIS;
//        If SQLHIS.SQLCode <> 0 OR SQLHIS.SQLNRows = 0 Then
//        If SQLHIS.SQLCode <> 0 Then
//                is_error = SQLHIS.SQLErrText
//        Else
//                is_error = "未找到更新记录或更新记录已变动!"
//        End If
//        is_error = '减少排队处方失败!'+ is_error
//        Return -1
//        End If
//        end if
//        Return 0


        return 0;
    }

    private static Integer refresh(Long cfsb) {
        QueryWrapper<MsCf02> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CFSB", cfsb);
        msCf02List = msCf02Service.list(queryWrapper);
        return 0;
    }

    private static Integer uffy() {
        String lsFphm;
        boolean lbYbzf = true;   ///lb_ybzf = gf_his_share_ybzx(il_cfsb,1) 原先写死了

        lsFphm = iuoMsCf01.getFphm();
        if(!lbYbzf && StringUtils.isBlank(lsFphm)) {
            isError = "该病人为医保病人，请先交费再进行发药！";
            return -1;
        }
        //判断该处方是否可发药
        if(checkcf() == -1) {
            return -1;
        }

        if(!ufIssueProcess(isPyr)) {
            return -1;
        }

        return 0;
    }

    private static boolean ufFyjz() {
//        s_his_share_brzh ls_brzh
//
//        IF Not iu_account.write_account(il_brid,is_brzh) THEN // 写帐户
//                is_error = SQLHIS.SQLErrText
//        RETURN False
//        END IF
//        IF Not iu_account.write_account_detail(il_sbxh,il_brid,"划价收费",6,0,is_brzh.zhsye,is_fphm,is_brzh.zhye) THEN
//                is_error = SQLHIS.SQLErrText
//        RETURN False
//        END IF
//
//        u_zh_public_bank lu_zh_public_bank
//        lu_zh_public_bank = create u_zh_public_bank
//        If Not lu_zh_public_bank.uf_account_xf(is_brzh.zhsye,il_brid,3,'划价收费',is_fphm) Then
//                is_error = lu_zh_public_bank.is_error
//        RETURN False
//        End If
//
//        IF idw_mzxx.Update(True,False) <> 1 THEN RETURN False //保存门诊信息
//        IF idw_sfmx.Update(True,False) <> 1 THEN RETURN False
//        IF idw_cf01.Update(True,False) <> 1 THEN RETURN False
//
//        RETURN True
        return true;
    }

    private static Integer checkcf() {
        if(iuoMsCf01.getFybz() > 0) {
            isError = "该处方单已被别的窗口发出!";
            return -1;
        }
        return 0;
    }

    private static boolean ufIssueProcess(String pyr) {
        Long llJlxh;
        Long llCfsb;
        Long llRowCount;
        Integer li_zcbz;

        if(ufGetMzxx() == 0) return false;


        if(iiJfbz == 1) {
            if(!ufFyjz()) {
                isError = "费用记账失败";
                return false;
            }
        }


//
//        Update MS_CF01 Set FYCK = :ii_ckbh, PYGH = :as_pyr,PYBZ = 1 Where cfsb = :il_cfsb and JGID = :go_jgxx.il_jgid using SQLHIS;
//
//        If SQLHIS.SQLCode <> 0 Then
//            is_error = SQLHIS.SQLERRTEXT
//            go_pools.uf_rollback_transaction("SQLHIS")
//            is_error = '处方信息更新失败' + is_error
//            Return false
//        End If
//
//        If issueprocess(as_pyr,3) = 0 Then
//            check_kcmx(li_zcbz)
//            if go_pools.uf_commit_transaction("SQLHIS") <= 0 then
//                is_error = '事务提交失败'  + is_error
//                return false
//            end if
//        Else
//            go_pools.uf_rollback_transaction("SQLHIS")
//            is_error = '发药失败' + is_error
//            return false
//        End If
//        idw_cf01.Reset()
//        idw_cf02.Reset()
//        Return true






        return true;
    }

    private static Integer ufGetMzxx() {
        ufInitBrzh();
        if(StringUtils.isNotBlank(iuoMsCf01.getFphm())) {
            iiJfbz = 0;
            return 1;
        } else {
            iiJfbz = 1;
        }

        return 1;
    }

    private static void caclSfmx(BigDecimal adDj, BigDecimal adSl, Long alFygb, BigDecimal adZfbl) {
        if(Objects.isNull(adDj)) adDj = new BigDecimal("0");
        if(Objects.isNull(adSl)) adSl = new BigDecimal("0");
        if(null == alFygb) alFygb = 0L;
        if(Objects.isNull(adZfbl)) adZfbl = new BigDecimal("0");

        BigDecimal bdZjje = adDj.multiply(adSl);
        bdZjje = bdZjje.setScale(2, BigDecimal.ROUND_HALF_UP);

        BigDecimal bdZfje = adDj.multiply(adSl).multiply(adZfbl);
        bdZfje = bdZfje.setScale(2, BigDecimal.ROUND_HALF_UP);

        if(bdZjje.compareTo(new BigDecimal("0")) == 1) {
            MsSfmx msSfmx = new MsSfmx();
            msSfmx.setJgid(1L);
            msSfmx.setSfxm(alFygb);
            msSfmx.setSfmc("");
            msSfmx.setZjje(bdZjje);
            msSfmx.setZfje(bdZfje);
            msSfmxList.add(msSfmx);
        }
    }

    private static void ufInitBrzh() {
        BigDecimal bigDecimal = new BigDecimal("0");
        hisShareBrzh.setGzze(bigDecimal);
        hisShareBrzh.setZhye(bigDecimal);
        hisShareBrzh.setLjfy(bigDecimal);
        hisShareBrzh.setZfdje(bigDecimal);
        hisShareBrzh.setCezfbl(bigDecimal);
        hisShareBrzh.setQtje(bigDecimal);
        hisShareBrzh.setZhlb(0);
        hisShareBrzh.setZhsye(bigDecimal);
        isFphm = "";
        ilSbxh = 0L;
    }
}